<template>
  <view>
    <view class="riliWrapper">
      <view class="riliWrapperBox">
        <!-- 固定的年月标题 -->
        <view class="fixed-month-title">
          <view class="month-nav-box" @click="prevMonth">
            <s-icon name="arrow-left" size="14" />
          </view>
          <view class="month-title-text">
            {{ year }}年{{ month < 10 ? '0' + month : month }}月 </view>
              <view class="month-nav-box" @click="nextMonth">
                <s-icon name="arrow" size="14" />
              </view>
          </view>

          <!-- 固定的星期行 -->
          <view class="fixed-week-header">
            <view class="week-number">
              <span v-for="(item, index) in weekList"
                :style="{ color: (index == 0 || index == weekList.length - 1) ? 'black' : '' }" :key="index">
                {{ item }}
              </span>
            </view>
          </view>

          <!-- 可滑动的日历内容 -->
          <view class="signWrapperCalendar">
            <view class="signWrapperCalendarBox">
              <swiper @change="_onClickSlideApi" duration="200" :current="slideDataListIndex" circular
                style="height:570rpx">
                <swiper-item class="swiper-item" v-for="(calendar, indexa) in 3" :key="indexa">
                  <view class="signWrapperCalendarBoxCenter">
                    <view class="signWrapperCalendarBoxCenterBox">
                      <view class="signWrapperCalendarBoxCenterBoxFooter">
                        <view class="each-day" v-for="(dayTime, idx) in processedDayList" :key="idx"
                          @click="selectDay(dayTime.date)">
                          <view :class="dayTime.dayClass">
                            <view class="eachDayBoxBox" :style="dayTime.dayStyle">
                              <view class="day-number">
                                <view style="text-align: center">{{ dayTime.date ? dayTime.date : '' }}</view>
                                <!-- 帮我加一个农历的  如果这天是节日 那么这里显示节日-->
                                <view class="nongli" style="text-align: center;font-size: 23rpx;">
                                  {{ dayTime.date ? getLunarDisplay(year, month, dayTime.date) : '' }}
                                </view>
                              </view>
                              <view class="lunar-day" v-if="dayTime">{{ getLunarDay(year, month, dayTime) }}</view>
                              <view class="markers" v-if="dayTime && getDayMarks(year, month, dayTime).length > 0">
                                <view class="marker-dot"
                                  v-for="(mark, mIndex) in getDayMarks(year, month, dayTime).slice(0, 5)" :key="mIndex"
                                  :style="{ backgroundColor: ' var(--v-theme)' }"></view>
                              </view>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </swiper-item>
              </swiper>
            </view>
          </view>
        </view>
      </view>
    </view>
</template>

<script>
import lunar from "./lunarCalendar.js";

export default {
  props: {
    // 从父组件传入的标记数据
    marksData: {
      type: Object,
      default: () => ({}),
    },
    // 从父组件传入的选中日期
    selectDate: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      weekList: ["日", "一", "二", "三", "四", "五", "六"],
      slideDataList: [],
      slideDataListIndex: 1,
      year: 2023,
      month: 6,
      day: 15,
      selectedDay: null,
      dayList: [],
      start_time: "",
      end_time: "",
      themeColor: "var(--v-theme)",
      // 默认标记颜色（当marksData中没有指定color时使用）
      defaultMarkColors: {
        work: "#FF6B6B", // 工作
        personal: "#4ECDC4", // 个人
        meeting: "#FFBE0B", // 会议
        reminder: "#A5A5A5", // 提醒
        holiday: "#FF9A9A", // 节假日
      },
    };
  },
  computed: {
    processedDayList() {
      return this.dayList.map(dayTime => {
        return {
          date: dayTime,
          dayClass: this.getDayBoxClass(dayTime),
          dayStyle: this.getDayStyle(dayTime)
        };
      });
    }
  },
  watch: {
    // 监听selectDate变化
    selectDate(newVal) {
      if (newVal) {
        this.parseSelectDate(newVal);
      }
    }
  },
  created() {
    uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });

    this._onLoad();
    // 初始化时解析selectDate
    if (this.selectDate) {
      this.parseSelectDate(this.selectDate);
    }
  },
  methods: {
    getLunarDisplay(year, month, day) {
      if (!day) return "";
      try {
        const lunarData = lunar.solarToLunar(year, month, day);

        // 农历节日判断
        const lunarFestivals = {
          '1-1': '春节',
          '1-15': '元宵节',
          '5-5': '端午节',
          '7-7': '七夕',
          '8-15': '中秋节',
          '9-9': '重阳节',
          '12-30': '除夕'
        };

        // 公历节日判断
        const solarFestivals = {
          '1-1': '元旦',
          '2-14': '情人节',
          '3-8': '妇女节',
          '4-1': '愚人节',
          '5-1': '劳动节',
          '6-1': '儿童节',
          '9-10': '教师节',
          '10-1': '国庆节',
          '12-24': '平安夜',
          '12-25': '圣诞节'
        };

        // 检查农历节日
        const lunarKey = `${lunarData.lunarMonth}-${lunarData.lunarDay}`;
        if (lunarFestivals[lunarKey]) {
          return lunarFestivals[lunarKey];
        }

        // 检查公历节日
        const solarKey = `${month}-${day}`;
        if (solarFestivals[solarKey]) {
          return solarFestivals[solarKey];
        }

        // 不是节日，正常显示农历信息
        if (lunarData.lunarDay === 1) {
          return lunarData.lunarMonthCn; // 初一显示月份
        }
        return lunarData.lunarDayCn; // 其他日期显示日期
      } catch (e) {
        console.error("农历计算错误:", e);
        return "";
      }
    },
    // 解析selectDate
    parseSelectDate(dateStr) {
      const parts = dateStr.split('-');
      if (parts.length === 3) {
        this.year = parseInt(parts[0]);
        this.month = parseInt(parts[1]);
        this.day = parseInt(parts[2]);
        this.selectedDay = this.day;
        this._runMonth();
      }
    },

    // 标准化日期格式
    normalizeDateStr(dateStr) {
      const parts = dateStr.split("-");
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      return `${year}-${month}-${day}`;
    },

    // 获取某天的标记（支持多种日期格式）
    getDayMarks(year, month, dayObj) {
      // 从dayObj中获取实际的日期数字
      const day = typeof dayObj === 'object' ? dayObj.date : dayObj;
      if (!day) return [];

      // 生成可能的日期格式
      const dateVariants = [
        `${year}-${month}-${day}`, // 2025-8-29
        `${year}-${month < 10 ? "0" + month : month}-${day < 10 ? "0" + day : day
        }`, // 2025-08-29
      ];

      // 检查所有可能的日期格式
      for (const dateStr of dateVariants) {
        if (this.marksData[dateStr]) {
          return this.marksData[dateStr].map((mark) => ({
            ...mark,
            color: mark.color || this.defaultMarkColors[mark.type],
          }));
        }

        // 尝试标准化后的格式
        const normalized = this.normalizeDateStr(dateStr);
        if (normalized !== dateStr && this.marksData[normalized]) {
          return this.marksData[normalized].map((mark) => ({
            ...mark,
            color: mark.color || this.defaultMarkColors[mark.type],
          }));
        }
      }
      return [];
    },

    // 上个月
    prevMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month = this.month - 1;
      }
      this._runMonth();
      this.selectedDay = null;
    },

    // 下个月
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month = this.month + 1;
      }
      this._runMonth();
      this.selectedDay = null;
    },

    // 获取日期框的class
    getDayBoxClass(dayTime) {
      if (!dayTime) return "eachDayBox";
      const isSelected = dayTime === this.selectedDay;
      const isToday = dayTime === this.day &&
        this.year === new Date().getFullYear() &&
        this.month === new Date().getMonth() + 1;

      if (isSelected && isToday) {
        return "eachDayBoxCheck eachDayBoxToday";
      } else if (isSelected) {
        return "eachDayBoxCheck";
      } else if (isToday) {
        return "eachDayBoxToday";
      }
      return "eachDayBox";
    },

    // 获取日期样式
    getDayStyle(dayTime) {
      if (dayTime === this.day &&
        this.year === new Date().getFullYear() &&
        this.month === new Date().getMonth() + 1) {
        return "border-bottom: 1rpx solid var(--v-theme);";
      }
      return "";
    },

    // 选择日期
    selectDay(dayTime) {
      if (!dayTime) return;
      this.selectedDay = dayTime;
      this.day = dayTime;
      const marks = this.getDayMarks(this.year, this.month, dayTime);

      // 通知父组件选中的日期
      this.$emit("day-selected", {
        year: this.year,
        month: this.month,
        day: dayTime,
        marks: marks,
      });

      // 更新selectDate
      this.$emit("update:selectDate", `${this.year}-${this.month}-${dayTime}`);
    },

    getLunarDay(year, month, day) {
      if (!day) return "";
      const lunarData = lunar.solarToLunar(year, month, day);
      if (lunarData.lunarDay === 1) {
        return lunarData.lunarMonthCn.replace("月", "");
      }
      return lunarData.lunarDayCn;
    },

    async _onLoad() {
      await this.initTime();
      await this._runMonth();
      this.selectedDay = this.day;
    },

    initTime() {
      var nowTimeData = this._getTimeNowApi();
      this.year = nowTimeData.year;
      this.month = nowTimeData.month;
      this.day = nowTimeData.day;
    },

    async _runMonth() {
      await this.initApi();
      await this._timeApi();
      let dataWeek = await this.getweek(this._getNowApi());
      this.slideDataList[0] = [];
      this.slideDataList[1] = dataWeek;
      this.slideDataList[2] = [];
    },

    _getTimeNowApi() {
      var date = new Date();
      var year = date.getFullYear();
      var month = parseInt(date.getMonth() + 1);
      var day = date.getDate();

      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }

      return {
        year: year,
        month: parseInt(month),
        day: day,
      };
    },

    _onClickSlideApi(e) {
      let current = e.detail.current;
      let oldIndex = this.slideDataListIndex;
      this.slideDataListIndex = current;

      if (oldIndex - current == -1 || oldIndex - current == 2) {
        if (this.month == 12) {
          this.year = this.year + 1;
          this.month = 1;
        } else {
          this.month = this.month + 1;
        }
      } else {
        if (this.month == 1) {
          this.year = this.year - 1;
          this.month = 12;
        } else {
          this.month = this.month - 1;
        }
      }
      this._runMonth();
      this.selectedDay = null;
    },

    _getNowApi() {
      return {
        Day: 1,
        Month: this.month,
        Year: this.year,
      };
    },

    initApi() {
      this.dayList = this.createDayList(this.month, this.year);
    },

    createDayList(month, year) {
      const count = this.getDayNum(month, year),
        _week = new Date(year + "/" + month + "/1").getDay();
      let list = [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
        21, 22, 23, 24, 25, 26, 27, 28,
      ];

      for (let i = 29; i <= count; i++) {
        list.push(i);
      }
      for (let i = 0; i < _week; i++) {
        list.unshift(null);
      }

      return list;
    },

    getDayNum(month, year) {
      let dayNum = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        dayNum[1] = 29;
      }
      return dayNum[month - 1];
    },

    _timeApi() {
      let startDate = this.year + "-" + this.month + "-" + this.day;
      let startData = this._timeMonthStartApi(startDate + " 00:00:00");
      this.start_time = startData.time_int;
      let endData = this._timeMonthEndApi(startDate + " 00:00:00");
      this.end_time = endData.time_int;
    },

    _timeMonthStartApi(timeDate) {
      var date = new Date(timeDate);
      date.setDate(1);
      var month = parseInt(date.getMonth() + 1);
      var day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }

      let timeDateStart = date.getFullYear() + "-" + month + "-" + day;

      return {
        time_type: "start_time",
        time_int: Date.parse(timeDateStart + " 00:00:00") / 1000,
        time_date: timeDateStart,
        year: date.getFullYear(),
        month: month,
        day: day,
      };
    },

    _timeMonthEndApi(timeDate) {
      var endDate = new Date(timeDate);
      var currentMonth = endDate.getMonth();
      var nextMonth = ++currentMonth;
      var nextMonthFirstDay = new Date(endDate.getFullYear(), nextMonth, 1);
      var oneDay = 1000 * 60 * 60 * 24;
      var lastTime = new Date(nextMonthFirstDay - oneDay);
      var endMonth = parseInt(lastTime.getMonth() + 1);
      var endDay = lastTime.getDate();
      if (endMonth < 10) {
        endMonth = "0" + endMonth;
      }
      if (endDay < 10) {
        endDay = "0" + endDay;
      }

      let timeDateEnd = endDate.getFullYear() + "-" + endMonth + "-" + endDay;

      return {
        time_type: "end_time",
        time_int: Date.parse(timeDateEnd + " 00:00:00") / 1000,
        time_date: timeDateEnd,
        year: endDate.getFullYear(),
        month: endMonth,
        day: endDay,
      };
    },

    getweek(date) {
      let dates = this.getDates(date);
      return dates;
    },

    getDates(date) {
      let dates = {
        year: date.Year,
        month: date.Month,
        firstDay: new Date(date.Year, date.Month, 1).getDay(),
        lastDay: new Date(date.Year, date.Month + 1, 0).getDay(),
        endDate: new Date(date.Year, date.Month + 1, 0).getDate(),
        weeks: [],
      };

      for (let i = dates.firstDay; i > 0; i--) {
        let dateinfo = {};
        dateinfo.date = new Date(date.Year, date.Month, -i + 1).getDate();
        dateinfo.isClick = false;
        dates.weeks.push(dateinfo);
      }
      for (
        let i = 1;
        i <= new Date(date.Year, date.Month + 1, 0).getDate();
        i++
      ) {
        let nowisClick = true;
        let dateinfo = {};
        dateinfo.date = i;
        if (this.dateType == "dateCustom") {
          nowisClick = false;
          if (
            this.dateCustom[dates.year] &&
            this.dateCustom[dates.year][dates.month]
          ) {
            for (
              let j = 0;
              j < this.dateCustom[dates.year][dates.month].length;
              j++
            ) {
              if (this.dateCustom[dates.year][dates.month][j] == i) {
                nowisClick = true;
              }
            }
          }
        }
        dateinfo.isClick = nowisClick;
        dates.weeks.push(dateinfo);
      }
      let len = 7 - dates.lastDay;
      if (42 - dates.weeks.length >= 7) {
        len += 7;
      }
      for (let i = 1; i < len; i++) {
        let dateinfo = {};
        dateinfo.date = i;
        dateinfo.isClick = false;
        dates.weeks.push(dateinfo);
      }
      return dates;
    },
  },
};
</script>

<style>
.riliWrapper {
  width: 100%;
  box-sizing: border-box;
  border-radius: 16rpx;
  box-shadow: var(--v-shadow);
  background: var(--v-white);
}

.riliWrapperBox {
  width: 100%;
}

.fixed-month-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: black;
  padding: 20rpx;
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 1rpx solid var(--v-bg);
}

.month-title-text {
  flex: 1;
  text-align: center;
}

.month-nav-box {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  cursor: pointer;
  transition: all 0.3s;
  background: rgba(0, 0, 0, 0.1);
  border: rgba(255, 255, 255, 0.2) 0.5px solid;
}

.fixed-week-header {
  width: 100%;
  padding: 10rpx 0;
  background-color: var(--v-white);
  position: sticky;
  top: 80rpx;
  z-index: 9;
  border-bottom: 1rpx solid var(--v-bg);
}

.week-number {
  display: flex;
  justify-content: space-around;
}

.week-number span {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: var(--v-gray);
}

.signWrapperCalendar {
  width: 100%;
  margin-top: 10rpx;
}

.signWrapperCalendarBox {
  width: 100%;
}

.signWrapperCalendarBoxCenter {
  width: 100%;
}

.signWrapperCalendarBoxCenterBox {
  width: 100%;
}

.signWrapperCalendarBoxCenterBoxFooter {
  display: flex;
  flex-wrap: wrap;
}

.each-day {
  width: calc(100% / 7);
  padding: 10rpx 0;
  box-sizing: border-box;
  cursor: pointer;
}

.eachDayBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  position: relative;
}

.eachDayBoxCheck {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background-color: var(--v-bg);
  border-radius: 8rpx;
  position: relative;
}

.eachDayBoxToday {
  /* border-bottom: 1rpx solid var(--v-theme); */
}

.eachDayBoxBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.day-number {
  font-size: 28rpx;
  color: #262626;
  /* color: var(--v-theme); */
  font-weight: bold;
}

.eachDayBoxCheck .day-number,
.eachDayBoxToday .day-number {
  color: var(--v-theme);
  font-weight: bold;
}

.lunar-day {
  font-size: 20rpx;
  color: var(--v-text-light);
  margin-top: 4rpx;
}

.eachDayBoxCheck .lunar-day,
.eachDayBoxToday .lunar-day {
  color: var(--v-theme);
}

.markers {
  position: absolute;
  top: 6rpx;
  right: 6rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.marker-dot {
  width: 16rpx;
  height: 6rpx;
  border-radius: 3px;
  margin: 2rpx 0;
}

.each-day[style*="opacity"] .day-number,
.each-day[style*="opacity"] .lunar-day {
  opacity: 0.5;
}

.week-number span:first-child,
.week-number span:last-child {
  color: var(--v-theme);
}
</style>